import { apiService, type ApiResponse } from './api'

export interface Note {
  _id: string
  userId: string
  title: string
  content: string
  tags?: string[]
  isPublic: boolean
  createdAt: string
  updatedAt: string
}

export interface CreateNoteData {
  title: string
  content: string
  tags?: string[]
  isPublic?: boolean
}

export interface UpdateNoteData extends CreateNoteData {}

export interface NotesListResponse {
  notes: Note[]
  pagination: {
    page: number
    limit: number
    total: number
    pages: number
  }
}

export interface SearchParams {
  page?: number
  limit?: number
  search?: string
  tags?: string[]
}

class NotesService {
  // 获取笔记列表
  async getNotes(params: SearchParams = {}): Promise<ApiResponse<NotesListResponse>> {
    const queryParams = new URLSearchParams()
    
    if (params.page) queryParams.append('page', params.page.toString())
    if (params.limit) queryParams.append('limit', params.limit.toString())
    if (params.search) queryParams.append('search', params.search)
    if (params.tags && params.tags.length > 0) {
      params.tags.forEach(tag => queryParams.append('tags', tag))
    }
    
    const queryString = queryParams.toString()
    const endpoint = queryString ? `/api/notes?${queryString}` : '/api/notes'
    
    return apiService.get<NotesListResponse>(endpoint)
  }

  // 获取单个笔记
  async getNoteById(id: string): Promise<ApiResponse<{ note: Note }>> {
    return apiService.get<{ note: Note }>(`/api/notes/${id}`)
  }

  // 创建笔记
  async createNote(data: CreateNoteData): Promise<ApiResponse<{ note: Note }>> {
    return apiService.post<{ note: Note }>('/api/notes', data)
  }

  // 更新笔记
  async updateNote(id: string, data: UpdateNoteData): Promise<ApiResponse<{ note: Note }>> {
    return apiService.put<{ note: Note }>(`/api/notes/${id}`, data)
  }

  // 删除笔记
  async deleteNote(id: string): Promise<ApiResponse<any>> {
    return apiService.delete(`/api/notes/${id}`)
  }

  // 搜索笔记
  async searchNotes(query: string): Promise<ApiResponse<{ notes: Note[] }>> {
    return apiService.get<{ notes: Note[] }>(`/api/notes/search?q=${encodeURIComponent(query)}`)
  }

  // 获取所有标签
  async getTags(): Promise<ApiResponse<{ tags: Array<{ name: string, count: number }> }>> {
    return apiService.get<{ tags: Array<{ name: string, count: number }> }>('/api/notes/tags')
  }
}

export const notesService = new NotesService()